package com.fp.m7.server.helpers;

import javax.servlet.http.HttpSession;

import nl.captcha.Captcha;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * A helper class for validation of captcha riddles. Makes use of the servlet context to withdraw the current request
 * and session to read the captcha attribute.
 * 
 * @author 7
 */
@Component
public class StickyCaptchaChecker {
    private final static Logger logger = LoggerFactory.getLogger(StickyCaptchaChecker.class);

    /**
     * Validate captcha: withdraw the current session form servlet ctx, and check captcha attribute.
     * 
     * @return true - is correct, false otherwise.
     */
    public boolean validateStickyCaptcha(String captchaText) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder
                .currentRequestAttributes();

        HttpSession session = servletRequestAttributes.getRequest().getSession();
        Captcha captcha = (Captcha) session.getAttribute(Captcha.NAME);

        if (captcha == null) {
            logger.warn("Captcha was not found in the session.");
            return false;
        }

        return captcha.isCorrect(captchaText);
    }
}
